<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="退料单号" prop="returnCode">
        <el-input v-model="queryParams.returnCode" placeholder="请输入退料单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工单编号" prop="workOrderCode">
        <el-input v-model="queryParams.workOrderCode" placeholder="请输入工单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="待审核" value="0" />
          <el-option label="已审核" value="1" />
          <el-option label="已执行" value="2" />
          <el-option label="已取消" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['production:return:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['production:return:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['production:return:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-check" size="mini" :disabled="single" @click="handleAudit"
          v-hasPermi="['production:return:audit']">审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-s-promotion" size="mini" :disabled="single" @click="handleExecute"
          v-hasPermi="['production:return:execute']">执行</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['production:return:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="returnList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="退料单ID" align="center" prop="returnId" />
      <el-table-column label="退料单编号" align="center" prop="returnCode" />
      <el-table-column label="工单编号" align="center" prop="workOrderCode" />
      <el-table-column label="领料单编号" align="center" prop="pickingCode" />
      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="退料人" align="center" prop="returnerName" />
      <el-table-column label="退料时间" align="center" prop="returnTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.returnTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === '0'" type="warning">待审核</el-tag>
          <el-tag v-else-if="scope.row.status === '1'" type="success">已审核</el-tag>
          <el-tag v-else-if="scope.row.status === '2'" type="info">已执行</el-tag>
          <el-tag v-else-if="scope.row.status === '3'" type="danger">已取消</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
            v-hasPermi="['production:return:query']">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['production:return:edit']" v-if="scope.row.status === '0'">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-check" @click="handleAudit(scope.row)"
            v-hasPermi="['production:return:audit']" v-if="scope.row.status === '0'">审核</el-button>
          <el-button size="mini" type="text" icon="el-icon-s-promotion" @click="handleExecute(scope.row)"
            v-hasPermi="['production:return:execute']" v-if="scope.row.status === '1'">执行</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['production:return:remove']" v-if="scope.row.status === '0'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改生产退料单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="退料单编号" prop="returnCode">
              <el-input v-model="form.returnCode" placeholder="请输入退料单编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单" prop="workOrderId">
              <el-select v-model="form.workOrderId" placeholder="请选择工单" clearable @change="handleWorkOrderChange" style="width: 100%">
                <el-option
                  v-for="order in workOrderList"
                  :key="order.orderId"
                  :label="`${order.orderCode} - ${order.productName}`"
                  :value="order.orderId">
                  <span style="float: left">{{ order.orderCode }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ order.productName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="领料单" prop="pickingId">
              <el-select v-model="form.pickingId" placeholder="请选择领料单" clearable @change="handlePickingChange" style="width: 100%">
                <el-option
                  v-for="picking in pickingList"
                  :key="picking.pickingId"
                  :label="picking.pickingCode"
                  :value="picking.pickingId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouseId">
              <el-select v-model="form.warehouseId" placeholder="请选择仓库" clearable style="width: 100%">
                <el-option
                  v-for="warehouse in warehouseList"
                  :key="warehouse.warehouseId"
                  :label="warehouse.warehouseName"
                  :value="warehouse.warehouseId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="退料人" prop="returnerId">
              <el-select v-model="form.returnerId" placeholder="请选择退料人" clearable style="width: 100%">
                <el-option
                  v-for="user in userList"
                  :key="user.userId"
                  :label="user.nickName"
                  :value="user.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退料时间" prop="returnTime">
              <el-date-picker clearable v-model="form.returnTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择退料时间" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="退料原因" prop="returnReason">
              <el-input v-model="form.returnReason" type="textarea" placeholder="请输入退料原因" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 退料明细 -->
        <el-divider content-position="left">退料明细</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddDetail">添加明细</el-button>
          </el-col>
        </el-row>
        <el-table :data="form.returnDetailList" style="width: 100%">
          <el-table-column label="物料编码" prop="materialCode" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.materialId" placeholder="请选择物料" clearable @change="handleMaterialChange(scope.$index, scope.row)" style="width: 100%">
                <el-option
                  v-for="material in materialList"
                  :key="material.materialId"
                  :label="material.materialCode"
                  :value="material.materialId">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" prop="materialName" width="150" />
          <el-table-column label="规格型号" prop="specification" width="120" />
          <el-table-column label="单位" prop="unit" width="80" />
          <el-table-column label="退料数量" prop="returnQuantity" width="120">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.returnQuantity" :min="0" :precision="2" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="批次号" prop="batchNumber" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.batchNumber" placeholder="请输入批次号" />
            </template>
          </el-table-column>
          <el-table-column label="退料原因" prop="returnReason">
            <template slot-scope="scope">
              <el-input v-model="scope.row.returnReason" placeholder="请输入退料原因" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteDetail(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReturn, getReturn, delReturn, addReturn, updateReturn, checkReturnCodeUnique, auditReturn, executeReturn } from "@/api/mes/production/return";
import { listPicking } from "@/api/mes/production/picking";
import { listWorkOrder } from "@/api/mes/production/workorder";
import { listWarehouse } from "@/api/mes/inventory/warehouse";
import { listMaterial } from "@/api/mes/basic/material";
import { listUser } from "@/api/system/user";

export default {
  name: "Return",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产退料单表格数据
      returnList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        returnCode: null,
        workOrderCode: null,
        status: null
      },
      // 表单参数
      form: {
        returnDetailList: []
      },
      // 表单校验
      rules: {
        returnCode: [
          { required: true, message: "退料单编号不能为空", trigger: "blur" }
        ],
        workOrderId: [
          { required: true, message: "工单不能为空", trigger: "change" }
        ],
        warehouseId: [
          { required: true, message: "仓库不能为空", trigger: "change" }
        ],
        returnerId: [
          { required: true, message: "退料人不能为空", trigger: "change" }
        ],
        returnTime: [
          { required: true, message: "退料时间不能为空", trigger: "blur" }
        ]
      },
      // 工单列表
      workOrderList: [],
      // 领料单列表
      pickingList: [],
      // 仓库列表
      warehouseList: [],
      // 物料列表
      materialList: [],
      // 用户列表
      userList: []
    };
  },
  created() {
    this.getList();
    this.getWorkOrderList();
    this.getPickingList();
    this.getWarehouseList();
    this.getMaterialList();
    this.getUserList();
  },
  methods: {
    /** 查询生产退料单列表 */
    getList() {
      this.loading = true;
      listReturn(this.queryParams).then(response => {
        this.returnList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取工单列表 */
    getWorkOrderList() {
      listWorkOrder({}).then(response => {
        this.workOrderList = response.rows;
      });
    },
    /** 获取领料单列表 */
    getPickingList() {
      listPicking({}).then(response => {
        this.pickingList = response.rows;
      });
    },
    /** 获取仓库列表 */
    getWarehouseList() {
      listWarehouse({}).then(response => {
        this.warehouseList = response.rows;
      });
    },
    /** 获取物料列表 */
    getMaterialList() {
      listMaterial({}).then(response => {
        this.materialList = response.rows;
      });
    },
    /** 获取用户列表 */
    getUserList() {
      listUser({}).then(response => {
        this.userList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        returnId: null,
        returnCode: null,
        workOrderId: null,
        pickingId: null,
        warehouseId: null,
        returnerId: null,
        returnTime: null,
        returnReason: null,
        status: "0",
        returnDetailList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.returnId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加生产退料单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const returnId = row.returnId || this.ids
      getReturn(returnId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改生产退料单";
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const returnId = row.returnId;
      getReturn(returnId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看生产退料单";
        // 设置表单为只读
        this.$nextTick(() => {
          this.$refs.form.$el.querySelectorAll('input, select, textarea').forEach(el => {
            el.disabled = true;
          });
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.returnId != null) {
            updateReturn(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReturn(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const returnIds = row.returnId || this.ids;
      this.$modal.confirm('是否确认删除生产退料单编号为"' + returnIds + '"的数据项？').then(function() {
        return delReturn(returnIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 审核按钮操作 */
    handleAudit(row) {
      const returnId = row.returnId || this.ids[0];
      this.$modal.confirm('是否确认审核该退料单？').then(function() {
        return auditReturn(returnId, "1");
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("审核成功");
      }).catch(() => {});
    },
    /** 执行按钮操作 */
    handleExecute(row) {
      const returnId = row.returnId || this.ids[0];
      this.$modal.confirm('是否确认执行该退料单？').then(function() {
        return executeReturn(returnId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("执行成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('production/return/export', {
        ...this.queryParams
      }, `return_${new Date().getTime()}.xlsx`)
    },
    /** 工单变化处理 */
    handleWorkOrderChange(value) {
      const workOrder = this.workOrderList.find(item => item.orderId === value);
      if (workOrder) {
        this.form.workOrderCode = workOrder.orderCode;
      }
    },
    /** 领料单变化处理 */
    handlePickingChange(value) {
      const picking = this.pickingList.find(item => item.pickingId === value);
      if (picking) {
        this.form.pickingCode = picking.pickingCode;
      }
    },
    /** 添加明细 */
    handleAddDetail() {
      this.form.returnDetailList.push({
        materialId: null,
        materialCode: null,
        materialName: null,
        specification: null,
        unit: null,
        returnQuantity: 0,
        batchNumber: null,
        returnReason: null
      });
    },
    /** 删除明细 */
    handleDeleteDetail(index) {
      this.form.returnDetailList.splice(index, 1);
    },
    /** 物料变化处理 */
    handleMaterialChange(index, row) {
      const material = this.materialList.find(item => item.materialId === row.materialId);
      if (material) {
        this.form.returnDetailList[index].materialCode = material.materialCode;
        this.form.returnDetailList[index].materialName = material.materialName;
        this.form.returnDetailList[index].specification = material.specification;
        this.form.returnDetailList[index].unit = material.unit;
      }
    }
  }
};
</script>